<template>
  <el-container class="app-container">
    <el-header class="main-header">
      <div class="header-left">
        <div class="logo-container">
          <el-icon class="logo-icon"><School /></el-icon>
          <span class="logo-text">在线考试系统</span>
        </div>
        <el-menu
          :default-active="activeMenu"
          class="nav-menu"
          mode="horizontal"
          background-color="#ffffff"
          text-color="#303133"
          active-text-color="#409EFF"
          :router="false"
        >
          <el-menu-item
            index="/student/exam-list"
            :disabled="isExamPage"
            @click="handleMenuClick('/student/exam-list')"
          >
            <el-icon><Calendar /></el-icon>
            <template #title>考试列表</template>
          </el-menu-item>
          <el-menu-item
            index="/student/score-inquiry"
            :disabled="isExamPage"
            @click="handleMenuClick('/student/score-inquiry')"
          >
            <el-icon><DataLine /></el-icon>
            <template #title>成绩查询</template>
          </el-menu-item>
          <el-menu-item
            index="/student/mistakes"
            :disabled="isExamPage"
            @click="handleMenuClick('/student/mistakes')"
          >
            <el-icon><Warning /></el-icon>
            <template #title>错题本</template>
          </el-menu-item>
          <el-menu-item
            index="/student/certificates"
            :disabled="isExamPage"
            @click="handleMenuClick('/student/certificates')"
          >
            <el-icon><Medal /></el-icon>
            <template #title>我的证书</template>
          </el-menu-item>
          <el-menu-item
            index="/student/profile"
            :disabled="isExamPage"
            @click="handleMenuClick('/student/profile')"
          >
            <el-icon><User /></el-icon>
            <template #title>个人中心</template>
          </el-menu-item>
        </el-menu>
      </div>
      
      <div class="header-right">
        <el-dropdown trigger="click" class="avatar-container">
          <div class="avatar-wrapper">
            <el-avatar :size="32" class="user-avatar">{{ userInfo.name.charAt(0) }}</el-avatar>
            <span class="user-name">{{ userInfo.name }}</span>
            <el-icon class="el-icon--right"><CaretBottom /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="router.push('/student/profile')">
                <el-icon><User /></el-icon>个人信息
              </el-dropdown-item>
              <el-dropdown-item @click="showPwdDialog = true">
                <el-icon><Lock /></el-icon>修改密码
              </el-dropdown-item>
              <el-dropdown-item divided @click="handleLogout">
                <el-icon><SwitchButton /></el-icon>退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>
    
    <el-main class="main-content">
      <router-view v-slot="{ Component }">
        <transition name="fade-transform" mode="out-in">
          <component :is="Component" />
        </transition>
      </router-view>
      <el-dialog v-model="showPwdDialog" title="修改密码" width="400px">
        <el-form :model="pwdForm" :rules="pwdRules" ref="pwdFormRef" label-width="100px">
          <el-form-item label="原密码" prop="oldPassword">
            <el-input v-model="pwdForm.oldPassword" type="password" show-password />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="pwdForm.newPassword" type="password" show-password />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="pwdForm.confirmPassword" type="password" show-password />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showPwdDialog = false">取消</el-button>
          <el-button type="primary" @click="handleChangePassword">确定</el-button>
        </template>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { School, Calendar, DataLine, Warning, User, CaretBottom, Lock, SwitchButton, Medal } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useUser } from '@/stores/userInfo'
import JSEncrypt from 'jsencrypt'

const router = useRouter()
const route = useRoute()
const userStore = useUser()

const activeMenu = computed(() => {
  return route.path
})

const userInfo = computed(() => ({
  name: userStore.userInfo.realName || userStore.userInfo.username || '未知用户',
  avatar: ''
}))

const showPwdDialog = ref(false)
const pwdForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
const pwdFormRef = ref(null)
const pwdRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const isExamPage = computed(() => {
  // 只在 /student/exam 或 /student/exam-paper 页面禁用，/student/exam-list 不禁用
  return (
    (/^\/student\/exam(\?|$)/.test(route.path + location.search))
    || route.path.startsWith('/student/exam-paper')
  )
})

function handleMenuClick(path) {
  if (isExamPage.value) {
    ElMessage.warning('考试中无法离开页面')
    return
  }
  router.push(path)
}

const handleLogout = () => {
  ElMessageBox.confirm('确认退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.clearUserInfo() // 清除用户信息
    router.push('/login')
  })
}

const handleChangePassword = async () => {
  if (!pwdFormRef.value) return
  try {
    await pwdFormRef.value.validate()
    // 加密新密码
    const publicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7rYgHiByM6LUO1Z7ZD80OKWl1O16/c+D1zRrrP5rYq/YSG+ZuP7Bjx3tcOgFmKL97ifyAbdNn9RmvyqBRqMt8YlT9vYXYQ8MirWbnBulhC9Q9j2ab/sUIDd1qdDIuAxx5i7X377M/IIrMTe1HTID646kwkKr/eUMZ1EEjX/Xnk2lJxj3sSzKuQ+LPMLrFQ1LP1jM6MNB4auDkrQ2vNEoI41gMy0PEE168nYrQWGkRdbolDX5GNDragi9my+Uv4J2hvf1GYDzDFs+FLK5ceUKFkkoGRHouqxkizxNAC2GlMGkJdKp2NXmvDdYvXl8VGutHPN2TnL2c875dRBEHb81zQIDAQAB'
    const encrypt = new JSEncrypt()
    encrypt.setPublicKey(publicKey)
    const encryptedOldPwd = encrypt.encrypt(pwdForm.value.oldPassword)
    const encryptedNewPwd = encrypt.encrypt(pwdForm.value.newPassword)
    const username = userStore.userInfo.username || userStore.userInfo.realName
    const token = sessionStorage.getItem('token')
    // 假设后端接口为 /updatePassword，GET 方式，参数 oldPassword、newPassword、username
    const params = `oldPassword=${encodeURIComponent(encryptedOldPwd)}&newPassword=${encodeURIComponent(encryptedNewPwd)}&username=${encodeURIComponent(username)}`
    const res = await fetch(`http://localhost:8080/updatePassword?${params}`, {
      method: 'GET',
      headers: {
        'Authorization': token ? `NERV_${token.replace(/^NERV_/, '')}` : ''
      }
    })
    const data = await res.json()
    if (data.code === 200) {
      ElMessage.success('密码修改成功，请重新登录')
      userStore.clearUserInfo()
      sessionStorage.removeItem('token')
      router.push('/login')
    } else {
      ElMessage.error(data.message || '密码修改失败')
    }
    showPwdDialog.value = false
    pwdForm.value.oldPassword = ''
    pwdForm.value.newPassword = ''
    pwdForm.value.confirmPassword = ''
  } catch (e) {
    // 验证失败会在表单中显示错误信息
  }
}
</script>

<style scoped>
.app-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-header {
  background: #fff;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  z-index: 1001;
}

.header-left {
  display: flex;
  align-items: center;
  height: 100%;
}

.logo-container {
  display: flex;
  align-items: center;
  margin-right: 40px;
}

.logo-icon {
  font-size: 24px;
  color: #0f76ddb5;
  margin-right: 8px;
}

.logo-text {
  color: #303133;
  font-size: 18px;
  font-weight: 600;
  white-space: nowrap;
}

.nav-menu {
  border-bottom: none;
  height: 100%;
}

.header-right {
  display: flex;
  align-items: center;
}

.avatar-container {
  cursor: pointer;
}

.avatar-wrapper {
  display: flex;
  align-items: center;
  padding: 0 8px;
  height: 100%;
  
  &:hover {
    background: rgba(0,0,0,.025);
  }
}

.user-avatar {
  background-color: #409EFF;
  color: #fff;
}

.user-name {
  margin: 0 8px;
  color: #606266;
}

.main-content {
  flex: 1;
  padding: 20px;
  background-color: #f0f2f5;
  overflow-y: auto;
}

/* 页面切换动画 */
.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.3s;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(30px);
}
</style>